package titt.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import titt.head.request.MethodHead;
import titt.head.request.RequestHead;
import titt.io.socket.TITTSocket;
import titt.key.KeyFactory;
import titt.server.func.TITTFunction;
import titt.server.os.ObjectServer;

public class ServerJobImpl implements ServerJob {

	private final Map<String, TITTFunction> funcs = new HashMap<String, TITTFunction>();
	private final TITTFunction def;
	private final ObjectServer os;
	
	public ServerJobImpl(ObjectServer os, TITTFunction def, TITTFunction... funcs) {
		this.def = def;
		this.os = os;
		for(TITTFunction f : funcs)
			this.funcs.put(f.getMethodName(), f);
	}
	
	@Override
	public void execute(RequestHead req, TITTSocket ts) throws IOException {
		try {
			MethodHead method = new MethodHead(req);
		
			String type = req.getPath().startsWith("/titt/") ? "titt" : null;
			
			String methodName = method.getMethodName();
			
			if(type != null) 
				if(methodName == null || !funcs.containsKey(methodName))
					ts.close();
				else {
					String tittPath = method.getNonMethodPath().substring(("/"+type).length());
					funcs.get(methodName).handle(KeyFactory.createKey(tittPath), method, ts, os);
				}
			else
				def.handle(KeyFactory.createKey(method.getNonMethodPath()), method, ts, os);
		}
		catch(IOException e) {
			throw e;
		}
		catch(Exception e) {
			throw new IOException(e);
		}
	}

}
